<template>
  <div>
    <div :class="{ wrap: isSticky }" :style="searchStyle" ref="element">
      <div :style="this.localParams[active].moreSearch?{flex: '0.9'}:{flex: '1'}">
        <van-search
          class="common_search"
          @search="confirm"
          @clear="clear"
          v-model="searchVal"
          :placeholder="placeholder"
          :maxlength="maxlength"
          width="120px"
          :show-action="show_action"
        >
      <template #action>
        <div style="display: flex;align-items: center;"  @click="onClickButton">
          <img style="width: 20px;" src="../../../assets/img/icon_filter_9.png"/>
          <span>筛选</span>
          </div>
      </template>
      </van-search>
      </div>
      <div :style="{flex: '0.1','background-color':'#e8f1f8'}" v-if="this.localParams[active].moreSearch" @click="searchMore()">
        <div class="search-more">
          <img
            style="height: 0.5rem"
            :src="this.localParams[active].moreValue?require('@/assets/Images/AppIcon/filter.png'):require('@/assets/Images/AppIcon/classification.png')"
          />
        </div>
      </div>
    </div>
    <div ref="elementTap">
      <van-tabs
        v-if="showTab"
        v-model="active"
        @change="change"
        :style="'padding-top: ' + listPaddingTop"
        :sticky="true"
        :offset-top="this.listPaddingTap"
        title-active-color="#00c1de"
      >
        <div v-for="(item, index) in this.localParams" :key="index"  >
          <van-tab :title="item.title" :badge="localParams[index].cnt" :name="index" >
            <van-dropdown-menu
              v-if="filterTab"
              active-color="#00c1de"
              style="background-color: #fff; margin: 5px 10px"
            >
              <van-dropdown-item
                v-for="(item, index) in filterParams"
                :key="index"
                :options="item.data"
                @change="handleChange2($event, item)"
                :title="item.title"
                @open="handledropdownOpen(item.name)"

              />
            </van-dropdown-menu>
            <van-list
              :finished="finished"
              v-model="loading"
              finished-text="没有更多了"
              @load="loadMore"
            >
              <slot />
            </van-list>
            <slot name="other" />
          </van-tab>
        </div>
        <slot name="customTab" />
      </van-tabs>
      <van-list
        v-if="!showTab"
        :finished="finished"
        v-model="loading"
        finished-text="没有更多了"
        :offset-top="this.listPaddingTap"
        :style="'padding-top: ' + listPaddingTop"
        :sticky="true"
        @load="loadMore"
      >
        <slot />
      </van-list>
      <slot name="bottomSlot" />
    </div>
  </div>
</template>
<script>
/**
 * PageTabList 带搜索tab过滤条件的分页列表
 * @property {String} placeholder 搜索栏Placeholder
 * @property {Number} maxlength 输入最大长度
 * @property {String} url 请求数据的path
 * @property {Object} params 搜索框条件对象
 *  params: {
      type: Array,
      default: () => [
        {
          title: "进行中的任务",
          badge: true,
          page: 0,
          limit: 10,
          dataType: "NotFinish",
        },
        {
          title: "未开始的任务",
          badge: false,
          page: 0,
          limit: 10,
          dataType: "NotStart",
        },
        {
          title: "已结束的任务",
          badge: false,
          page: 0,
          limit: 10,
          dataType: "Finished",
        },
      ],
    },
 * @event {Function} initList 数据回调    @initList="_initList" 返回数据为list
 * _initList(list){
      this.list = list
    },
  *filterParams: [
      {
        name: "Status",
        title: "状态",
        originTitle:"状态",
        dataType: "int",
        data: [
          { text: "不限", value: "" },
          { text: "未发行", value: "0" },
          { text: "现行", value: "10" },
          { text: "废止", value: "-1" },
        ],
      },
    ],
  *activeFilter:[
    {
      active:0,
      filter:false,
    }
  ]
 */
import { deepClone } from "@/utils";
import { ref } from "vue";

export default {
  name: "eagle-tab-page-list",
  props: {
    placeholder: {
      type: String,
      default: "搜索",
    },
    showTab: {
      type: Boolean,
      default: true,
    },
    maxlength: {
      type: [Number, String],
      default: 100,
    },
    value: {
      type: [Number, String],
      default: "",
    },
    url: {
      type: String,
      default: "",
    },
    params: {
      type: Array,
      default: () => [],
    },
    filterTab: {
      type: Boolean,
      default: false,
    },
    filterParams: {
      type: Array,
      default: () => [],
    },
    activeFilter: {
      type: Array,
      default: () => [],
    },
    isSticky: {
      type: Boolean,
      default: true,
    },
    //搜索栏的筛选按钮
    show_action:{
      type: Boolean,
      default: false
    },
    
    filterParamsDefaul: {
      type: Array,
      default: () => [],
    },
    active:{
      type: Number,
      default: 0,

    },
    noNeedData:{
      type:Number,
      default:-1,
    }
  },
// setup(){
// const activeName=ref('1')
// return {activeName}
// },
  data() {
    return {
      dd:'IAPT00001',
      searchVal: "",
      localParams: [],
      resetParams: [],
      // active: 0,
      conditions: [],
      list: [],
      loading: false,
      finished: false,
      count: 0,
      navHeight: 0,
      listPaddingTop: 0,
      listPaddingTap: 0,
      first: false,
      selFilterParams: [],
      isFirstLoad: false,
      searchStyle: {display: "flex" },
      activeName:1,
   
    };
  },
  watch: {
    value: {
      immediate: true,
      handler(newSearchVal) {
        this.searchVal = newSearchVal;
      },
    },
    searchVal(newVal, oldVal) {
      this.$emit("input", newVal);
    },
    params: {
      handler(preParams) {
        preParams.forEach((item, index, arr) => {
          Object.assign(this.localParams[index], item);
        });
      },
      deep: true,
    },
  },
  created() {
    //将params参数 复制给localParams
    for (let i = 0; i < this.params.length; i++) {
      this.localParams.push(
        Object.assign(
          { page: 0, limit: 20, badge: false, cnt: "",moreSearch:false },
          this.params[i]
        )
      );
    }
    this.resetParams = deepClone(this.localParams);
    this.first = true;
    this.isFirstLoad = true;
    console.log("this.active    "+this.active)
    // this.active = 1;
    console.log(this.localParams)
    for (var i = 0; i < this.localParams.length; i++) {
      if (i == 0 || this.localParams[i].badge) {
         this.getList(i);
      }
    }
  },
  mounted() {
    if (this.isSticky) {
      this.navHeight =
        document.getElementsByClassName("van-nav-bar")[0].offsetHeight + "px";
      this.listPaddingTop = window.getComputedStyle(this.$refs.element).height;
      this.listPaddingTap =
        Number(this.listPaddingTop.replace("px", "")) +
        Number(
          window
            .getComputedStyle(this.$refs.elementTap)
            .height.replace("px", "")
        );
      this.searchStyle.top = this.navHeight;
    }
  },
  methods: {
    handledropdownOpen(name){
    
      this.$emit("onClickDropdown",name);

    },
    onClickButton() {
     
      this.$emit("onClickSearchButton");
    },
    change() {
      this.selFilterParams=[]
      for(var i=0;i<this.filterParams.length;i++){
        let item = this.filterParams[i];
        item.title = item.originTitle;
      }
      this.$emit("initActive", this.active);
      if (this.list) {
        this.list.splice(0, this.list.length);
      }
      this.loading = false;
      this.finished = false;
      // if(this.filterParams && this.filterParams.length>0){
      //   for(var i=0;i<this.filterParams.length;i++){
      //     let item = this.filterParams[i];
      //     item.title = item.originTitle;
      //   }
      // }
      this.confirm();
    },
    clear() {
      this.searchVal = "";
      this.localParams = this.resetParams;
      this.confirm();
    },
    confirm() {
      this.isFirstLoad = false;
      this.localParams[this.active].page = 0;
      var conditions = [];
      if (this.searchVal) {
        conditions.push({
          Name: "Keywords",
          DisplayName: this.searchVal,
          Value: this.searchVal,
          Operator: "like",
          DataType: "String",
        });
      }

      if (this.isFilter()) {
        this.selFilterParams.forEach((condition) => {
          // if (condition.data[0] && condition.data[0].value) {
          if (condition.data[0] ) {
            conditions.push({
              Name: condition.name,
              DisplayName: condition.data[0] && condition.data[0].text,
              Value: condition.data[0] && condition.data[0].value,
              Operator: "=",
              DataType: condition.dataType ? condition.dataType : "String",
            });
          }
        });
      }
    
      this.localParams[this.active].conditions = JSON.stringify(conditions);
      this.getList(this.active);
    },
    getList(currentActive) {
      
      if(this.noNeedData==currentActive)return
      if (!currentActive) {
        currentActive = this.active;
      }
      this.loading = true;
      this.finished = false;
      let _this = this;
      // this.localParams[currentActive].applyArea="广东省"
      _this.$axios
        .get(_this.url, { params: _this.localParams[currentActive] })
        // .get(_this.url, { params: _this.params[currentActive] })
        .then((res) => {
          console.log(_this.localParams[currentActive])
          _this.loading = false;
          if (!res.data.HasNextPage) {
            _this.finished = true;
          }
          _this.list = res.data.Data;
          //   this.count = res.data.TotalCount > 99 ? "99+" : res.data.TotalCount;
          if (_this.localParams[currentActive].badge) {
            _this.localParams[currentActive].cnt =
              res.data.TotalCount > 99 ? "99+" : res.data.TotalCount;
          } else {
            _this.localParams[currentActive].cnt = "";
          }
          _this.localParams.forEach((item) => {
            if (!item.badge) {
            }
          });
          _this.localParams[currentActive].page = res.data.PageIndex;
          if (_this.isFirstLoad) {
            if (currentActive === 0) {
              _this.$emit("initActive", currentActive);
              _this.$emit("initList", _this.list);
            }
          } else {
            _this.$emit("initActive", _this.active);
            _this.$emit("initList", _this.list);
          }
          _this.first = false;
        })
        .catch((err) => {
          console.log("err", err);
          _this.finished = true;
        });
    },
    loadMore() {
      this.isFirstLoad = false;
      if (!this.first) {
        this.loading = true;
        ++this.localParams[this.active].page;
        let _this = this;
        _this.$axios
          .get(this.url, { params: this.localParams[this.active] })
          .then((res) => {
            _this.loading = false;
            _this.localParams[_this.active].page = res.data.PageIndex;
            _this.list = _this.list.concat(res.data.Data);
            if (!res.data.HasNextPage) {
              _this.finished = true;
            }
            _this.$emit("initActive", _this.active);
            _this.$emit("initList", _this.list);
          })
          .catch((err) => {
            console.log("err", err);
            _this.finished = true;
          });
      }
    },
    handleChange(value, data) {
      this.loading = false;
      this.finished = false;
      this.selFilterParams = deepClone(this.filterParams);
      this.selFilterParams.filter((item) => {
        var filterItems=[]
        filterItems= item.data.filter((it) => {
          var ischoose=false
          if( it.value === value){
            data.title = it.text;  
            ischoose=true 
          }
          return ischoose;
        });
         
        if(filterItems==null||filterItems.length==0){
          filterItems.push(item.data[0])
        }
        item.data=filterItems
        return item;
      });
      this.confirm();
    },
    handleChange2(value, data) {

      this.loading = false;
      this.finished = false;

      if(!this.selFilterParams.length){
 
        this.selFilterParams = deepClone(this.filterParams);
        this.selFilterParams.filter((item) => {
        var filterItems=[]
        filterItems= item.data.filter((it) => {
          var ischoose=false
          if( it.value === value){
            data.title = it.text;  
            ischoose=true 
          }
          return ischoose;
        });
         
        if(filterItems==null||filterItems.length==0){
          filterItems.push(item.data[0])
        }
        item.data=filterItems
        return item;
      });
      }else{
        this.selFilterParams.map((item)=>{
          if(item.name==data.name){
      
      
            item.data[0].value=value
       
            var nameTemp
            for (let i = 0; i < data.data.length; i++) {
                if(value==null||data.data[i].value==value){
          
                  nameTemp=data.data[i].text
                }
            }
            data.title=nameTemp
            item.data[0].text=nameTemp
          }
        })
      }

      this.confirm();
    },
    isFilter() {
      if (this.activeFilter.length == 0) {
        return true;
      }
      let myActiveArr = this.activeFilter.filter((item) => {
        return item.active == this.active;
      });
      if (myActiveArr.length == 0) {
        return true;
      }
      return myActiveArr[0].filter;
    },
    searchMore() {
      this.$emit("searchMore");
    },
  },
};
</script>
<style lang="less" scoped>
.wrap {
  width: 100%;
  position: fixed;
  z-index: 1000;
}

/deep/ .van-tabs__nav {
  margin: 0 10px !important;
}

/deep/ .van-dropdown-menu__bar {
  background-color: #fff;
}

/deep/ .van-dropdown-item {
  margin: 0 10px !important;
}

.search-more {
  text-align: center;
  vertical-align: middle;
  overflow: hidden;
  margin-top: 0.5rem;
}
</style>